package com.example.edu.config;

import com.alibaba.druid.pool.DruidDataSource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.sql.DataSource;
import java.sql.SQLException;

/**
 * @author yanzhao
 * @date 2022/1/11 17:26
 * @since 1.0.0
 */
@Configuration
public class DatasourceConfig {

    private Logger logger = LoggerFactory.getLogger(DatasourceConfig.class);

    @Value("${datasource.url:jdbc:mysql://127.0.0.1:3306/test?charset=utf8mb4&useSSL=false}")
    private String url;

    @Value("${datasource.username:root}")
    private String username;

    @Value("${datasource.password:}")
    private String password;

    @Bean
    public DataSource dataSource() {

        DruidDataSource dataSource = new DruidDataSource();
        dataSource.setName("druid");
        dataSource.setDbType("mysql");
        dataSource.setDriverClassName("com.mysql.cj.jdbc.Driver");
        dataSource.setUrl(url);
        dataSource.setUsername(username);
        dataSource.setPassword(password);

        dataSource.setMaxActive(20);
        dataSource.setInitialSize(10);

        // 配置获取连接等待超时的时间
        dataSource.setMaxWait(60000);
        // 配置间隔多久才进行一次检测，检测需要关闭的空闲连接，单位是毫秒
        dataSource.setTimeBetweenEvictionRunsMillis(60000);

        dataSource.setTestWhileIdle(true);
        dataSource.setTestOnBorrow(true);
        dataSource.setValidationQuery("select 1");

        dataSource.setPoolPreparedStatements(true);
        dataSource.setMaxPoolPreparedStatementPerConnectionSize(20);

        try {
            dataSource.setFilters("stat,wall,log4j");
        } catch (SQLException e) {
            logger.error("druid configuration Exception", e);
        }
        return dataSource;
    }

}
